package com.promotores;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.promotores.jsonparsing.JSONParser;
import com.promotores.jsonparsing.JSONReader2;
import com.promotores.jsonparsing.JSONReaderListener;
import com.promotores.util.Parametros;

public class JsonTipoPromocion {
	
	// url to make request
	private static String url = "http://200.16.7.112:3000/promoter_management/promotions/promotion_types/";
	//private static String url = "http://200.16.7.112:3000/promoter_management/promotions.json";
		
	// JSON Node names
	private static final String TAG_TIPOPROMOCION = "promotion";
	private static final String TAG_CREATED_AT = "created_at";
	private static final String TAG_DESCRIPCION = "descripcion";
	private static final String TAG_ID = "id";
	private static final String TAG_UPDATED_AT = "updated_at";	
	private static final String TAG_DELETED = "deleted";
	// contacts JSONArray
	JSONArray promociones = null;
	
	public List<BeanTipoPromocion> read(Context context){
		List<BeanTipoPromocion> lstTipoPromociones = new ArrayList<BeanTipoPromocion>();
				
		// Creating JSON Parser instance
		//JSONParser jParser = new JSONParser();
		String read = url+Parametros.getLast_update()+"(yyyy-MM-dd'T'HH:mm:ss'Z').json";
		//String readValues = jParser.read(read);
		
		JSONReader2 jReader = new JSONReader2();
		jReader.setJSONReaderListener((JSONReaderListener)context);
		try {
			//JSONArray jsonArray = new JSONArray(readValues);
			JSONArray jsonArray =(jReader.execute(read)).get();
			
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);			
							
				// Storing each json item in variable				
				int id = jsonObject.getJSONObject(TAG_TIPOPROMOCION).getInt(TAG_ID);
				String descripcion = jsonObject.getJSONObject(TAG_TIPOPROMOCION).getString(TAG_DESCRIPCION);
				String created_at = jsonObject.getJSONObject(TAG_TIPOPROMOCION).getString(TAG_CREATED_AT);
				String updated_at = jsonObject.getJSONObject(TAG_TIPOPROMOCION).getString(TAG_UPDATED_AT);
				String deleted = jsonObject.getJSONObject(TAG_TIPOPROMOCION).getString(TAG_DELETED);
				//String deleted = "0";
				
				BeanTipoPromocion tipoPromocion = new BeanTipoPromocion();
				tipoPromocion.setId(id);
				tipoPromocion.setTipoPromocion(descripcion);
				tipoPromocion.setCreated_at(created_at);
				tipoPromocion.setUpdated_at(updated_at);
				tipoPromocion.setDeleted(deleted);
				lstTipoPromociones.add(tipoPromocion);
			}
		} catch (Exception e) {
			System.out.println("Json: Exception");
			e.printStackTrace();
			return null;
		}
		return lstTipoPromociones;
	}
	
}
